<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert title="注意，只允许为第三级分类设置相关参数" type="warning" show-icon>
      </el-alert>
      <el-row class="rowP">
        <el-col :span="2.5">
          <p>选着商品分类：</p>
        </el-col>
        <el-col :span="20">
          <el-cascader clearable v-model="paramsKeys" :options="paramsinfolist" :props="props" @change="paramsChanged">
          </el-cascader>
        </el-col>
      </el-row>
      <!-- tabs标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button :disabled="isDisabled" type="primary" @click="addParamsBtn">添加参数</el-button>
          <!-- 表格数据 -->
          <el-table :data="manyDataList" border>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- tag标签展示 -->
                <el-tag :key="i" v-for="(item,i) in scope.row.attr_vals" closable :disable-transitions="false"
                  @close="handleClose(scope.row,i)">{{item}}
                </el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#">
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" @click="editParams(scope.row)" size="mini" icon="el-icon-edit">修改</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteParamsBtn(scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button :disabled="isDisabled" type="primary" @click="addAttributeBtn">添加属性</el-button>
          <!-- 表格数据 -->
          <el-table :data="onlyDataList" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- tag标签展示 -->
                <el-tag :key="i" v-for="(item,i) in scope.row.attr_vals" closable :disable-transitions="false"
                  @close="handleClose(scope.row,i)">{{item}}
                </el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="editParams(scope.row)">修改</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteParamsBtn(scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- Dialog 添加参数，添加属性对话框 -->
    <el-dialog @close="clearAddForm" :title="'添加'+getPublicTitle" :visible.sync="addParamsDialogVisible" width="40%">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="getPublicTitle" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框区域 -->
    <el-dialog @close="editclearAddForm" :title="'修改'+getPublicTitle" :visible.sync="editParamsDialogVisible"
      width="40%">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="getPublicTitle" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsPri">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>
<script>
export default {
  data () {
    return {
      // 初始化，参数列表数据
      paramsinfolist: [],
      paramsKeys: [],
      props: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },
      // tabs标签页
      activeName: 'many',
      onlyDataList: [],
      manyDataList: [],
      // 添加参数/属性对话框显示关闭
      addParamsDialogVisible: false,
      // 添加属性或者添加参数的表单数据源
      addForm: {},
      // 验证规则
      addFormRules: {
        attr_name: [{ required: true, message: '请输入参数', trigger: 'blur' }]
      },
      // 修改参数的对话框启动项
      editParamsDialogVisible: false,
      // 修改表单的数据源
      editForm: {},
      // 修改表单的验证规则
      editFormRules: {
        attr_name: [{ required: true, message: '请输入参数', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.getParamsList()
  },
  methods: {
    // 初始获取参数列表
    async getParamsList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return
      this.paramsinfolist = res.data
    },
    // 参数列表改变，促发监听事件
    paramsChanged () {
      if (this.paramsKeys.length !== 3) {
        this.paramsKeys = []
        this.onlyDataList = []
        this.manyDataList = []
        return
      }
      this.getParamsData()
    },
    // 获取表单的数据
    async getParamsData () {
      console.log(this.activeName)
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      )
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals.trim() ? item.attr_vals.trim().split(' ') : []
        item.inputValue = ''
        item.inputVisible = false
      })
      console.log(res.data)
      if (this.activeName === 'only') {
        this.onlyDataList = res.data
      } else {
        this.manyDataList = res.data
        console.log(this.manyDataList)
      }
    },
    // ,tabs标签页点击事件
    handleClick (tab) {
      if (this.cateId == null) {
        return
      }
      this.getParamsData()
      console.log(this.activeName)
    },
    // 添加参数按钮
    addParamsBtn () {
      this.addParamsDialogVisible = true
    },
    // 添加属性按钮
    addAttributeBtn () {
      this.addParamsDialogVisible = true
    },
    clearAddForm () {
      this.$refs.addFormRef.resetFields()
    },
    addParams () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) return this.$message.error('添加参数失败')
        this.getParamsData()
        this.$message.success('添加参数成功')
        this.addParamsDialogVisible = false
      })
    },
    // 修改参数按钮
    async editParams (row) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_sel: this.activeName
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改失败')
      }
      this.editForm = res.data
      this.editParamsDialogVisible = true
    },
    // 重置修改表单数据
    editclearAddForm () {
      this.$refs.editFormRef.resetFields()
    },
    // 修改参数确认按钮,
    editParamsPri () {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 200) return this.$message.error('修改参数失败')
        this.$message.success('修改参数成功')
        this.getParamsData()
        this.editParamsDialogVisible = false
      })
    },
    // 删除参数
    async deleteParamsBtn (row) {
      const confirm = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((error) => error)
      console.log(confirm)
      if (confirm !== 'confirm') {
        return this.$message.info('取消删除成功')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${row.attr_id}`
      )
      if (res.meta.status !== 200) return this.$message.error('删除参数失败')
      this.$message.success('删除参数成功')
      this.getParamsData()
    },
    // 关闭标签触发事件
    handleClose (row, i) {
      row.attr_vals.splice(i, 1)
      this.getAttributeData(row)
    },
    // tag输入框触发事件
    handleInputConfirm (row) {
      if (!row.inputValue.trim()) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue)
      this.getAttributeData(row)
      row.inputValue = ''
      row.inputVisible = false
    },
    async getAttributeData (row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('添加失败')
    },
    // 标签按钮
    showInput (row) {
      console.log(row)
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  },
  computed: {
    // 是否禁用按钮
    isDisabled () {
      if (this.paramsKeys.length === 3) {
        return false
      } else {
        return true
      }
    },
    cateId () {
      if (this.paramsKeys.length === 3) {
        return this.paramsKeys[2]
      }
      return null
    },
    getPublicTitle () {
      if (this.activeName === 'only') {
        return '静态属性'
      } else {
        return '动态参数'
      }
    }
  }
}
</script>
<style lang="less" scoped>
.el-alert {
  margin-bottom: 10px;
}
.rowP {
  line-height: 40px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag{
  width: 100px;
}
</style>
